﻿/*
 * jQuery Nested list to google org chart plugin
 *
 * Copyright (c) 2010 Tim Farland (http://www.timfarland.com)
 * Licensed under the GPL license and MIT:
 *   http://www.opensource.org/licenses/GPL-license.php
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Converts targeted <ol> and <ul> elements to google org charts
 *
 * Project home: http://www.timfarland.com/nested-list-to-google-org-chart
 *
 * Requires google org chart package:
 * http://code.google.com/apis/visualization/documentation/gallery/orgchart.html
 *
 * Revision: $Id$
 * Version: 0.1
 * 
 */

(function($) {
 
   //plugin init
   $.fn.g_orgchart = function(config) { 	    

	var opts = $.extend({}, $.fn.g_orgchart.defaults, config);
	    
		//apply to each element
		return this.each(function() {
		  
			var $this = $(this);
					  					  
			//build tree object
			$.fn.g_orgchart.trav($this, '');
						
			//draw google org chart
			$.fn.g_orgchart.draw_chart($this.attr('id'), opts);
						
			//reset obj
			$.fn.g_orgchart.conv_obj = [];
   
		  
		});
	
	 
	   };
   
   
   	// default config
	$.fn.g_orgchart.defaults = {
	
		allowHtml:true
	
	};
	
	   
	//data object for g chart
	$.fn.g_orgchart.conv_obj = [];
	
	
	//outerHTML function 
	//snippet from http://www.briangrinstead.com/blog/jquery-outerhtml-snippet
	$.fn.outerHTML = function() {
	    var doc = this[0] ? this[0].ownerDocument : document;
	    return $('<div>', doc).append(this.eq(0).clone()).html();
	};
   
   
   
   	//ul traversal func
	$.fn.g_orgchart.trav = function(target, parent){
  
    		target.children("li").each(function(order){
									    
			var id = parent + '_' + order;
			
			//the a tag will determine the contents of the node
			$(this).children().not('ul, ol').each(function(i){					
												
				$.fn.g_orgchart.conv_obj.push([{v:id+'', f: $(this).outerHTML() }, parent+'', $(this).attr('title') ]);	
				
			});			
			
			//any uls found in the li will be traversed recursively
			//after check to prevent too much recursion
			if ($(this).children("ul, ol").length > 0){						
				$(this).children("ul, ol").each(function(ulindex){
					$.fn.g_orgchart.trav($(this), id);									
				});	
			}			
		});  
    }
    
        
    
    
    //draw org chart
    $.fn.g_orgchart.draw_chart = function(target, opts) {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Id');
        data.addColumn('string', 'Parent');
        data.addColumn('string', 'Text');
        data.addRows($.fn.g_orgchart.conv_obj);
        var chart = new google.visualization.OrgChart(document.getElementById(target));	   
        chart.draw(data, opts);
      }





  })(jQuery) ;